package ar.com.niktutos.dao.impl;

import java.util.List;
import java.io.Serializable;
import java.lang.reflect.*;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import ar.com.niktutos.dao.GenericDAO;
import ar.com.niktutos.dto.CapituloDTO;

public abstract class AbstractGenericDAOImpl<INSTANCE_CLASS, PRIMARY_KEY_CLASS extends Serializable> implements GenericDAO<INSTANCE_CLASS, PRIMARY_KEY_CLASS>{
	
	protected SessionFactory sessionFactory;
	private Class<INSTANCE_CLASS> persistentClass;
   
    public AbstractGenericDAOImpl() {
    	
        this.persistentClass = (Class<INSTANCE_CLASS>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];

   }
    
	@SuppressWarnings("unchecked")
	public INSTANCE_CLASS findById(PRIMARY_KEY_CLASS id) {
		Session sess = sessionFactory.openSession();
    	INSTANCE_CLASS entity = null;
    	try{
    		entity = (INSTANCE_CLASS) sess.get(this.persistentClass,id);
    	} finally {
		     sess.close();
		}
        return entity;
    }
	
    public void add(INSTANCE_CLASS instance) {
    	 Session sess = sessionFactory.openSession();
		 Transaction tx = null;
		 try {
		     tx = sess.beginTransaction();
		     sess.saveOrUpdate(instance);
		     tx.commit();
		 }
		 catch (Exception e) {
		     if (tx!=null) tx.rollback();
		     e.printStackTrace();
		 }
		 finally {
		     sess.close();
		 }
		 
    }

    public void merge(INSTANCE_CLASS instance) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void remove(PRIMARY_KEY_CLASS id) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public INSTANCE_CLASS findById(PRIMARY_KEY_CLASS id, Class<?> fetchingStrategy, Object... args) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    
    public List<INSTANCE_CLASS> findAll() {
    	throw new UnsupportedOperationException("Not supported yet.");
		 
    }

    public List<INSTANCE_CLASS> findAll(Class<?> fetchingStrategy, Object... args) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public List<INSTANCE_CLASS> findAll(int pageNumber, int pageSize) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
   
}
